package com.main.sales.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.main.sales.common.R;
import com.main.sales.dto.OrdersDto;
import com.main.sales.pojo.OrderDetail;
import com.main.sales.pojo.Orders;
import com.main.sales.pojo.ShoppingCart;
import com.main.sales.pojo.User;
import com.main.sales.service.OrderDetailService;
import com.main.sales.service.OrdersService;
import com.main.sales.service.ShoppingCartService;
import com.main.sales.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    //http://localhost:8080/order/submit
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        ordersService.submit(orders);
        return R.success("订单已提交");
    }

    //http://localhost:8080/order/page?
    // page=1&
    // pageSize=10&
    // number=123&
    // beginTime=2022-08-01%2000%3A00%3A00&
    // endTime=2022-09-14%2023%3A59%3A59

    /**
     * 后台订单明详
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page<OrdersDto>> page(int page, int pageSize, String number, String beginTime, String endTime) {
//        log.info("订单明细：{}，{}，{}，{}，{}", page, pageSize, number, beginTime, endTime);
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        //按条件查询
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(number != null, Orders::getNumber, number);//订单号
        lqw.between(beginTime != null, Orders::getOrderTime, beginTime, endTime);//时间范围
        lqw.orderByDesc(Orders::getOrderTime);//按照下单时间排序
        ordersService.page(pageInfo, lqw);//分页数据


        List<Orders> records = pageInfo.getRecords();//获取分页数据
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long userId = item.getUserId();//订单用户id
            User byId = userService.getById(userId);
            if (byId != null) {
                String name = byId.getName();
                ordersDto.setUserName(name);
            }
            String id = item.getNumber();//订单号
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> list = orderDetailService.list(lambdaQueryWrapper);//订单明详
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        log.info("后台订单明详{}", ordersDtoList);
        return R.success(ordersDtoPage);
    }

    //http://localhost:8080/order/userPage?page=1&pageSize=5

    /**
     * 用户界面订单明细
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        ordersService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
//        log.info("用户界面订单明细{}",records);
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            String number = item.getNumber();//订单号
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId, number);
            List<OrderDetail> list = orderDetailService.list(lqw);//订单明详
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
//        log.info("ordersDtoList{}",ordersDtoList);
        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }


    //http://localhost:8080/order

    /**
     * 订单派送
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders) {
        ordersService.updateById(orders);
        return R.success("订单已派送");
    }



    /**
     * 再来一单
     *
     * @param orders
     * @return
     */
//    @PostMapping("/again")
    public R<String> again(HttpSession session, @RequestBody Orders orders) {
        log.info("再来一单{}", orders);
        //获取订单号 id
        Long id = orders.getId();
        //根据订单号查订单明细表  order_id
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId, id);
        //此订单的所有商品
        List<OrderDetail> list = orderDetailService.list(lqw);

        //清空购物车
        LambdaQueryWrapper<ShoppingCart> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(ShoppingCart::getUserId, session.getAttribute("user"));
        log.info("用户id：{}",session.getAttribute("user"));
        shoppingCartService.remove(lqw2);


        return R.success("----");
    }

}
